
package com.android.fitnesscenter.view.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.fitnesscenter.R;
import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.ConfigProperties.QueryDetailResult;
import com.android.fitnesscenter.utils.ConfigProperties.TradingType;
import com.android.fitnesscenter.utils.ActivityHelper;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.MapEntity;
import com.android.fitnesscenter.utils.TimerHelper;
import com.android.fitnesscenter.utils.ViewHelper;
import com.android.fitnesscenter.view.SelectBaseActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

public class ClientDetailActivity extends SelectBaseActivity {

    private ListView listview;
    private QueryDetailListAdapter mQueryDetailListAdapter;

    @ViewInject(R.id.txt_empty)
    private TextView txt_empty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.query_detail_layout);
        ViewUtils.inject(this);
        initView();
    }

    private void initView() {
        initTitleBar(getString(R.string.txt_find_detail));
        mScreenWidth = ActivityHelper.getScreenWidth(this) / 2;
        txt_user.setVisibility(View.GONE);
        listview = (ListView) findViewById(R.id.listview);
        mQueryDetailListAdapter = new QueryDetailListAdapter();
        listview.setAdapter(mQueryDetailListAdapter);

        mList = new ArrayList<MapEntity>();
        mOperateStrs = new String[] {
                "全部", "充值", "缴费"
        };
        queryDetail(getToken(), mCurOperate, mCurDate);
    }

    private void queryDetail(String token, String type, String date) {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        String imei = getIMEI();
        params.addBodyParameter("token", token);
        params.addBodyParameter("imei", imei);
        if (!TextUtils.isEmpty(type)) {
            params.addBodyParameter("type", type);
        }
        if (!TextUtils.isEmpty(date)) {
            params.addBodyParameter("date", date);
        }

        String url = ConfigProperties.SERVICE_URL + "queryUserDetail.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                mDialog = new ProgressDialog(ClientDetailActivity.this);
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("查询账户明细中,请等待...");
                mDialog.show();
                if (mList != null) {
                    mList.clear();
                }
                if (mQueryDetailListAdapter != null) {
                    mQueryDetailListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ClientDetailActivity.this != null && !ClientDetailActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                boolean success = jsonObject.getBoolean("success");
                                if (success) {
                                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                                    int length = jsonArray.length();
                                    for (int i = 0; i < length; i++) {
                                        JSONObject jSObject = (JSONObject) jsonArray.get(i);
                                        String id = jSObject.getString(QueryDetailResult.ID_STR);
                                        String createTime = jSObject.getString(QueryDetailResult.CREATE_TIME_STR);
                                        String status = jSObject.getString(QueryDetailResult.STATUS_STR);
                                        String type = jSObject.getString(QueryDetailResult.TYPE_STR);
                                        String money = jSObject.getString(QueryDetailResult.MONEY_STR);
                                        MapEntity entity = new MapEntity();
                                        entity.setValue(QueryDetailResult.ID, id);
                                        entity.setValue(QueryDetailResult.CREATE_TIME, createTime);
                                        entity.setValue(QueryDetailResult.STATUS, status);
                                        entity.setValue(QueryDetailResult.MONEY, money);
                                        entity.setValue(QueryDetailResult.TYPE, type);
                                        mList.add(entity);
                                    }
                                } else {
                                    String msg = jsonObject.getString("message");
                                    if (TextUtils.equals(msg, "查询用户帐户出错")) {
                                        mList.clear();
                                    } else {
                                        new ViewHelper(ClientDetailActivity.this).showBTNDialog(msg);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ClientDetailActivity.this).showBTNDialog("账户明细查找失败,请重试!");
                    }
                    if (mList == null || mList.size() == 0) {
                        txt_empty.setVisibility(View.VISIBLE);
                    } else {
                        txt_empty.setVisibility(View.GONE);
                    }
                    mQueryDetailListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                if (ClientDetailActivity.this != null && !ClientDetailActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    Loger.e("onFailure msg is " + msg);
                    new ViewHelper(ClientDetailActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    private class QueryDetailListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(ClientDetailActivity.this).inflate(R.layout.query_detail_list_item,
                        null);
                viewHolder = new ViewHolder();
                viewHolder.txt_type = (TextView) convertView.findViewById(R.id.txt_type);
                viewHolder.txt_value = (TextView) convertView.findViewById(R.id.txt_value);
                viewHolder.txt_time = (TextView) convertView.findViewById(R.id.txt_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            bindView(viewHolder, position);
            return convertView;
        }

        @SuppressLint("SimpleDateFormat")
        private void bindView(ViewHolder viewHolder, int position) {
            MapEntity entity = mList.get(position);
            String type = entity.getString(QueryDetailResult.TYPE);
            String money = entity.getString(QueryDetailResult.MONEY);
            String tradingType = "";
            if (TextUtils.equals(type, TradingType.PAY)) {
                tradingType = getString(R.string.txt_pay);
                money = "-" + money;
                viewHolder.txt_value.setTextColor(getResources().getColor(R.color.holo_red_light));
            } else if (TextUtils.equals(type, TradingType.TOP_UP)) {
                money = "+" + money;
                tradingType = getString(R.string.txt_top_up);
                viewHolder.txt_value.setTextColor(getResources().getColor(R.color.holo_green_light));
            }
            String createTime = entity.getString(QueryDetailResult.CREATE_TIME);
            viewHolder.txt_type.setText(tradingType);
            viewHolder.txt_value.setText(money);
            viewHolder.txt_time.setText(TimerHelper.formatTime(createTime));
        }

        public class ViewHolder {
            public TextView txt_type;
            public TextView txt_value;
            public TextView txt_time;
        }

    }

    @Override
    protected void titlebarMethod(int id) {
        switch (id) {
            case R.id.txt_operate:
                mCurType = 1;
                showPopWindows();
                break;
            case R.id.txt_time:
                selectTime();
                break;
        }
    }

    @Override
    protected List<HashMap<String, String>> getDataByType() {
        String[] valuesStrs = mOperateStrs;
        List<HashMap<String, String>> title_list = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < valuesStrs.length; i++) {
            HashMap<String, String> map_title = new HashMap<String, String>();
            map_title.put("title", valuesStrs[i]);
            title_list.add(map_title);
        }
        return title_list;
    }

    @Override
    protected void requestData(String token, String user, String operate, String date) {
        String tradingType = "";
        if (TextUtils.equals("充值", operate)) {
            tradingType = TradingType.TOP_UP;
        } else if (TextUtils.equals("缴费", operate)) {
            tradingType = TradingType.PAY;
        }
        queryDetail(token, tradingType, date);
    }
}
